<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 11:35
 */


namespace App\Logic\Tenant;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Staffer\Staffer;
use App\Models\Tenant;
use Arr;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;

class TenantLogic extends CommLogic
{
    /**
     * @param $params
     * @return mixed
     */
    public function lists($params)
    {
        $query = Tenant::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->get()->toArray();

        return $data;
    }

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Tenant::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();

        foreach($data["data"] as &$item){
            $item['logo'] = Arr::first(array_column(json_decode($item['logo'], true), 'url'));
        }

        return $data;
    }

    /**
     * @param $params
     * @return bool
     * @throws \Throwable
     */
    public function store($params)
    {
        $lockName = 'tenant_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        $code = substr(md5(Tenant::query()->count()), 0, 6);
        try {
            list($valid_start, $valid_end) = $params['valid_time'];
            $data = array(
                'name' => $params['name'],
                'status' => $params['status'],
                'valid_end_at' => $valid_end,
                'valid_start_at' => $valid_start,
                'domain' => $code,
                'logo' => json_encode($params['logo'], true),
                'copyright' => $params['copyright'] ?? '',
                'host' => $params['host'] ?? '',
                'database' => $params['database'] ?? '',
                'port' => $params['port'] ?? '',
                'account' => $params['account'] ?? '',
                'password' => $params['password'] ?? '',
                'wx_appid' => $params['wx_appid'] ?? '',
                'wx_secret' => $params['wx_secret'] ?? '',
                'login_background' => $params['login_background'] ?? '',
                'remark' => $params['remark'] ?? '',
            );
            Tenant::query()->create($data);
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $params
     * @param $id
     * @return Tenant|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($params, $id)
    {
        $tenant = Tenant::query()->where('id', $id)->first();
        abort_if(empty($tenant), HttpCode::FORBIDDEN, '找不到租户');
        $tenant->logo = json_decode($tenant->logo, true);
        $tenant->valid_time = array($tenant->valid_start_at, $tenant->valid_end_at);
        return $tenant;
    }

    /**
     * @param $params
     * @param $id
     * @return bool
     * @throws \Throwable
     */
    public function update($params, $id)
    {

        $lockName = 'tenant_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $tenant = Tenant::query()->where('id', $id)->first();
        abort_if(empty($tenant), HttpCode::FORBIDDEN, '找不到租户');
        \DB::beginTransaction();
        try {
            
            list($valid_start, $valid_end) = $params['valid_time'];
            $data = array(
                'name' => $params['name'],
                'status' => $params['status'],
                'valid_end_at' => $valid_end,
                'valid_start_at' => $valid_start,
                'logo' => json_encode($params['logo'], true),
                'copyright' => $params['copyright'] ?? '',
                'login_background' => $params['login_background'] ?? '',
                'host' => $params['host'] ?? '',
                'database' => $params['database'] ?? '',
                'port' => $params['port'] ?? '',
                'account' => $params['account'] ?? '',
                'password' => $params['password'] ?? '',
                'wx_appid' => $params['wx_appid'] ?? '',
                'wx_secret' => $params['wx_secret'] ?? '',
                'remark' => $params['remark'] ?? '',
            );
            $tenant->update($data);
            if ($params['status'] <> 1) {
                Staffer::query()->where('tenant_id', $id)->update(['status', 0]);
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  [type] $id
     */
    public function destroy($id)
    {
        $data = Tenant::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '找不到租户');
        return $data->delete() ? true : false;
    }
}
